package com.tl.mqtt.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageCallback implements MqttCallback {

    private Logger logger = LoggerFactory.getLogger(MessageCallback.class);
    private MqttClient client;
    private MqttConnectOptions options;
    private String topic;
    private int qos;

    private MessageCallback(){
        //构造方法私有化
    }

    public MessageCallback(MqttClient client, MqttConnectOptions options, String topic, int qos) {
        this.client = client;
        this.options = options;
        this.topic = topic;
        this.qos = qos;
    }

    @Override
    public void connectionLost(Throwable throwable) {
        try {
            logger.info("MQTT断开重连");
            client.connect(options);
            Thread.sleep(1000);
            //logger.info("重新订阅主题{},质量QOS：{}",topic,qos);
            //client.unsubscribe(topic);
            //client.subscribe(topic,qos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void messageArrived(String topic, MqttMessage msg) throws Exception {
        logger.info("主题名称：{}",topic);
        byte[] payload = msg.getPayload();
        logger.info("主题消息：{}",new String(payload,"UTF-8"));
    }


    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        logger.info("发布结果：{}",token.isComplete());
    }

}
